﻿using System;
using System.Data;
using System.Data.Common;
using System.Data.OracleClient;

namespace PKTools.Database
{
    public class OracleSql : Sql
    {
        public OracleSql(string connection, OracleConnection outerConnection) 
            : base(connection, outerConnection == null)
        {
        }

        public override DbParameter AddInput(string key, object value, Type type = null)
        {
            var
                p = new OracleParameter(key, value ?? DBNull.Value);
            this.command.Parameters.Add(p);
            return p; 
        }

        public override DbParameter AddOutput(string key, Type type)
        {
            type = GetFinalType(type);

            object
                value = null;
            if (type.IsValueType)
                value = Activator.CreateInstance(type);

            var
                p = new OracleParameter(key, value)
                {
                    Direction = ParameterDirection.Output
                };

            this.command.Parameters.Add(p);
            return p;
        }

        protected override void SetupQuery(string query, params object[] objs)
        {
            base.SetupQuery(query, objs);

            foreach (DbParameter p in this.command.Parameters)
                this.command.CommandText = this.command.CommandText.Replace('@' + p.ParameterName, ':' + p.ParameterName);
        }
    }
}
